import { FC, useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import type { ChartConfig } from '../../../types/report';
import styles from './ChartPreview.module.css';

interface ChartPreviewProps {
  config: ChartConfig;
}

const ChartPreview: FC<ChartPreviewProps> = ({ config }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts>();

  useEffect(() => {
    if (!chartRef.current) return;

    if (!chartInstance.current) {
      chartInstance.current = echarts.init(chartRef.current);
    }

    const option = {
      title: {
        text: config.title
      },
      tooltip: {
        trigger: 'axis'
      },
      ...config.options,
      series: [{
        type: config.type,
        data: config.data
      }]
    };

    chartInstance.current.setOption(option);

    return () => {
      chartInstance.current?.dispose();
      chartInstance.current = undefined;
    };
  }, [config]);

  return (
    <div 
      ref={chartRef} 
      className={styles.chartPreview}
    />
  );
};

export default ChartPreview; 